package org.sqp.wbnet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.FormBody;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sqp.conn.Browser;
import org.sqp.wbnet.model.UserInfo;
import org.sqp.wbnet.model.WbAd;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class WbActions {
    private static Logger logger = LoggerFactory.getLogger(WbActions.class);

    public static void index(Browser browser){
        String url = "http://www.cpwbnet.com";
        try(Response response = browser.request(browser.getRequestBuilder().url(url).get().build())){
            // set cookie
        }
    }

    public static List<WbAd> getAds(Browser browser) {
        String url = "http://www.cpwbnet.com/api.php?t=1546320519263&action=queryAD";

        final List<WbAd> ads = new ArrayList<>();
        try (Response response = browser.request(browser.getRequestBuilder().url(url).get().build())){
            if (response != null) {
                String resp = response.body().string();
                logger.debug(resp);
                JSONObject jsonObject = JSON.parseObject(resp);
                JSONArray items = jsonObject.getJSONArray("items");
                items.forEach(obj -> {
                    JSONObject job = (JSONObject) obj;
                    WbAd ad = new WbAd();
                    ad.setImageId(job.getInteger("imageId"));
                    ad.setLink(job.getString("link"));
                    ad.setUrl(job.getString("url"));
                    ads.add(ad);
                });
                logger.debug(ads.toString());
            }
        } catch (Exception e) {
            //
        }
        return ads;
    }

    public static UserInfo getUserInfo(Browser browser, String sid) {
        String url = "http://www.cpwbnet.com/api.php?t=" + timestamp() + "&action=getUserInfo";
        FormBody formBody = new FormBody.Builder().add("sid", sid).build();
        try (Response response = browser.request(browser.getRequestBuilder().url(url).post(formBody).build())){
            JSONObject jsonObject = JSON.parseObject(response.body().string());
            UserInfo ui = new UserInfo();
            ui.setAccId(jsonObject.getString("AccID"));
            ui.setBandWitth(jsonObject.getString("BandWidth"));
            ui.setDisDate(jsonObject.getString("DisDate"));
            ui.setName(jsonObject.getString("UserName"));
            return ui;
        } catch (Exception e) {
            //
            logger.info("查询用户信息失败");
        }
        return null;
    }

    public static void credit(Browser browser, String sid, WbAd wbAd) {
        String url = "http://www.cpwbnet.com/api.php?t=" + timestamp() + "&action=credit99";
        FormBody formBody = new FormBody.Builder().add("sid", sid).add("imageId", String.valueOf(wbAd.getImageId())).build();
        try (Response response = browser.request(browser.getRequestBuilder().url(url).post(formBody).build())){
            logger.debug(" http-" + wbAd.getImageId() + "-" + response.code());
        }
    }

    public static String login(Browser browser, String userName, String password) {
        String url = "http://www.cpwbnet.com/api.php?t=" + timestamp() + "&action=login";
        FormBody formBody = new FormBody.Builder().add("username", userName).add("password", password).build();
        try (Response response = browser.request(browser.getRequestBuilder().url(url).post(formBody).build())){
            JSONObject jsonObject = JSON.parseObject(response.body().string());
            Boolean success = jsonObject.getBoolean("success");
            if (!success) {
                logger.debug("登录失败，用户名密码错误");
                return null;
            }
            //sid
            return jsonObject.getString("sid");
        } catch (Exception e) {
            logger.debug("登录失败");
            return null;
        }

    }


    public static String timestamp() {
        return String.valueOf(System.currentTimeMillis());
    }
}
